package com.example.shutdown;

import java.util.Calendar;
import java.util.List;
import java.util.ArrayList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.ContentValues;
import org.litepal.crud.DataSupport;

import android.os.Handler;
import android.provider.Settings;
/**
 * 
 * @ClassName: AlarmReceiver
 * @Description:开机启动AlarmService 每隔60秒由系统Alarm唤醒这个Receiver检查AlarmService是否正在运行
 * @author jachary.zhao
 * @date 2013-11-25 下午4:44:30
 * 
 */
public class AlarmReceiver extends BroadcastReceiver {
	private String TAG = "yu_AlarmReceiver";
	private Context mContext;
	private String POWER_ON_ACTION = "rk.android.turnontime.action"; 
	private String POWER_OFF_ACTION = "rk.android.turnofftime.action";
	private String REBOOT_ACTION = "rk.android.reboottime.action";
	private String CLOSE_ALL = "rk.android.rtc.closeAll";
	private String CAT_ALL = "rk.android.rtc.catAll";
	private final static String POWER_MANAGER_ENABLE = "power_enable";

	// private String SLEEPMODE_ACTION = "rk.android.realsleepmode.action";
	// //睡眠模式
	// private static final String ACTION_REQUEST_SHUTDOWN =
	// "android.intent.action.ACTION_REQUEST_SHUTDOWN";
	public void onReceive(Context context, Intent intent) {
		this.mContext = context;

		Intent alarmServiceIntent = new Intent(context, AlarmService.class);
		String action = intent.getAction();

		// if(!isServiceRunning("com.example.shutdown.AlarmService")){
		// Log.d(TAG,"-----AlarmService Not Running!------");
		// Toast.makeText(context, "-------AlarmService Not Running!---------",
		// Toast.LENGTH_LONG).show();
		// mContext.startService(alarmServiceIntent);
		// }
		if (null != action) {
			if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
				SharedPreferences sharedPreferences = context.getSharedPreferences("zhao", Context.MODE_PRIVATE);
				boolean firstRun = sharedPreferences.getBoolean("first", true);
				if (firstRun) {
					List<PowerPlan> initPowerPlans = new ArrayList<PowerPlan>();
					for (int i = 1; i <= 7; i++) {
						initPowerPlans.add(new PowerPlan(false, false,i, 23, 59, 8,30));
					}
					DataSupport.saveAll(initPowerPlans);
					firstRun = false;
					sharedPreferences.edit().putBoolean("first", firstRun).commit();
				}
				boolean isInitHistoryUptime = Settings.System.getInt(context.getContentResolver(), "init_history_uptime", 0) == 1;
				Log.d(TAG, "-------------------------isInitHistoryUptime-----------------"+ isInitHistoryUptime);
				if (!isInitHistoryUptime) {
					Settings.System.putString(context.getContentResolver(),"last_boot_time", null);
					Settings.System.putString(context.getContentResolver(),"last_shut_time", null);
					Settings.System.putString(context.getContentResolver(),"last_up_time", null);
					Settings.System.putString(context.getContentResolver(),"total_uptime_seconds", null);
					Settings.System.putString(context.getContentResolver(),"last_uptime_seconds", null);
					Settings.System.putString(context.getContentResolver(),"history_up_time", null);
					Settings.System.putInt(context.getContentResolver(),"init_history_uptime", 1);
					Settings.System.putInt(context.getContentResolver(),"show_history_uptime", 0);
					List<Uptime> initUptimes = DataSupport.findAll(Uptime.class);
					if (initUptimes != null && initUptimes.size() > 0) {
						DataSupport.deleteAll(Uptime.class);
					}
				}
				String lastBootTime = Settings.System.getString(context.getContentResolver(), "last_boot_time");
				String lastShutTime = Settings.System.getString(context.getContentResolver(), "last_shut_time");
				String lastUptime = Settings.System.getString(context.getContentResolver(), "last_up_time");
				Log.d(TAG, "----lastBootTime------" + lastBootTime);
				Log.d(TAG, "----lastShutTime------" + lastShutTime);
				Log.d(TAG, "----lastUptime--------" + lastUptime);
				String lastUptimeSeconds = Settings.System.getString(
						context.getContentResolver(), "last_uptime_seconds");
				String totalUptimeSeconds = Settings.System.getString(
						context.getContentResolver(), "total_uptime_seconds");
				String newTotalUptimeSeconds = null;
				if (!TextUtils.isEmpty(lastUptimeSeconds)) {
					if (!TextUtils.isEmpty(totalUptimeSeconds)) {
						newTotalUptimeSeconds = String.valueOf(Long.valueOf(lastUptimeSeconds)+ Long.valueOf(totalUptimeSeconds));
					} else {
						newTotalUptimeSeconds = lastUptimeSeconds;
					}
					Settings.System.putString(context.getContentResolver(),"total_uptime_seconds", newTotalUptimeSeconds);
				}
				List<Uptime> uptimes = DataSupport.findAll(Uptime.class);
				if (uptimes.size() == 5) {
					uptimes.remove(0);
					DataSupport.delete(Uptime.class, uptimes.get(0).getId());
				}
				if (!TextUtils.isEmpty(lastBootTime) && !TextUtils.isEmpty(lastShutTime) && !TextUtils.isEmpty(lastUptime)) {
					Uptime uptime = new Uptime();
					uptime.setBootTime(lastBootTime);
					uptime.setShutTime(lastShutTime);
					uptime.setUpTime(lastUptime);
					uptime.save();
					uptimes.add(uptime);
				}
				StringBuilder sb = new StringBuilder();
				for (Uptime uptime2 : uptimes) {
					Log.d(TAG, "---id---" + uptime2.getId()
							+ "---BootupTime---" + uptime2.getBootTime()
							+ "---Uptime---" + uptime2.getUpTime()
							+ "---Shutdowntime---" + uptime2.getShutTime());
					sb.append(context.getResources().getString(R.string.bootup_time));
					sb.append(uptime2.getBootTime() + "\t\t");
					sb.append(context.getResources().getString(R.string.up_time));
					sb.append(uptime2.getUpTime() + "\t\t");
					sb.append(context.getResources().getString(R.string.shutdown_time));
					sb.append(uptime2.getShutTime() + "\n");
				}
				Settings.System.putString(context.getContentResolver(),"history_up_time", sb.toString());
				mContext.startService(alarmServiceIntent);
			} else if (action.equals(POWER_OFF_ACTION)) {
				SharedPreferences sharedPreferences = context.getSharedPreferences("zhao", Context.MODE_PRIVATE);
				boolean firstRun = sharedPreferences.getBoolean("first", true);
				if (firstRun) {
					List<PowerPlan> initPowerPlans = new ArrayList<PowerPlan>();
					for (int i = 1; i <= 7; i++) {
						initPowerPlans.add(new PowerPlan(false,false, i, 23, 59, 8,30));
					}
					DataSupport.saveAll(initPowerPlans);
					firstRun = false;
					sharedPreferences.edit().putBoolean("first", firstRun).commit();
				}
				int offHour = 0;
				int offMin = 0;
				boolean enable = intent.getBooleanExtra("enable", false);
				String offHourString = intent.getStringExtra("offHour");
				String offMinString = intent.getStringExtra("offMin");
				String offWeekString = intent.getStringExtra("offWeek");
				if(enable){
					if (!TextUtils.isEmpty(offHourString) && !TextUtils.isEmpty(offMinString)) {
						String tempOffHour = offHourString.trim();
						String tempOffMin = offMinString.trim();
						if(tempOffHour.length()>0 && tempOffMin.length()>0){
							try{
								offHour = Integer.parseInt(tempOffHour);
								offMin = Integer.parseInt(tempOffMin);
								if(offHour>=0 && offHour<24 && offMin>=0 && offMin<60){
									ContentValues values = new ContentValues();
									values.put("powerOffEnable", enable);
									values.put("offHour", offHour);
									values.put("offMin", offMin);
									if (TextUtils.isEmpty(offWeekString)) {
										Calendar calendar = Calendar.getInstance();
										DataSupport.updateAll(PowerPlan.class, values,"week = ?",  calendar.get(Calendar.DAY_OF_WEEK)+ "");
									} else {
										String weekString = offWeekString.trim();
										if (weekString.equals("0")) {
											for (int i = 1; i < 8; i++) {
												DataSupport.updateAll(PowerPlan.class, values,"week = ?", String.valueOf(i));
											}
										} else {
											DataSupport.updateAll(PowerPlan.class, values,"week = ?", weekString);
										}
									}
									if (enable) {
										sharedPreferences.edit().putBoolean(POWER_MANAGER_ENABLE, enable).commit();
									}
									mContext.startService(alarmServiceIntent);
								}
							}catch(NumberFormatException e){
								Log.d(TAG, "--POWER_OFF_ACTION--"+e.toString());
							}
						}
					}
				}else{
					if (!TextUtils.isEmpty(offWeekString)) {
						String weekString = offWeekString.trim();
						if (weekString.equals("0")) {
							for (int i = 1; i < 8; i++) {
								updatePowerOffEnable(false,String.valueOf(i));//Close All
							}
						}else{
							updatePowerOffEnable(false,weekString);
						}
						mContext.startService(alarmServiceIntent);
					}
				}
				Log.d(TAG, "-------------------offWeekString:"+offWeekString+"---offHourString:"+offHourString+"---offMinString:"+offMinString);
			} else if (action.equals(POWER_ON_ACTION)) {
				SharedPreferences sharedPreferences = context.getSharedPreferences("zhao", Context.MODE_PRIVATE);
				boolean firstRun = sharedPreferences.getBoolean("first", true);
				if (firstRun) {
					List<PowerPlan> initPowerPlans = new ArrayList<PowerPlan>();
					for (int i = 1; i <= 7; i++) {
						initPowerPlans.add(new PowerPlan(false, false,i, 23, 59, 8,30));
					}
					DataSupport.saveAll(initPowerPlans);
					firstRun = false;
					sharedPreferences.edit().putBoolean("first", firstRun).commit();
				}
				int onHour = 0;
				int onMin = 0;
				boolean enable = intent.getBooleanExtra("enable", false);
				String onHourString = intent.getStringExtra("onHour");
				String onMinString = intent.getStringExtra("onMin");
				String onWeekString = intent.getStringExtra("onWeek");
				if (TextUtils.isEmpty(onHourString) || TextUtils.isEmpty(onMinString)) {
					enable = intent.getBooleanExtra("turnonenable", false);
					onHourString = intent.getStringExtra("turnonhour");
					onMinString = intent.getStringExtra("turnonmin");
				}
				if(enable){
					if (!TextUtils.isEmpty(onHourString) && !TextUtils.isEmpty(onMinString)) {
						String tempOnHour = onHourString.trim();
						String tempOnMin = onMinString.trim();
						if(tempOnHour.length()>0 && tempOnMin.length()>0){
							try{
								onHour = Integer.parseInt(tempOnHour);
								onMin = Integer.parseInt(tempOnMin);
								if(onHour>=0 && onHour<24 && onMin>=0 && onMin<60){
									ContentValues values = new ContentValues();
									values.put("powerOnEnable", enable);
									values.put("onHour", onHour);
									values.put("onMin", onMin);
									if (TextUtils.isEmpty(onWeekString)) {
										Calendar calendar = Calendar.getInstance();
										int todayWeek = calendar.get(Calendar.DAY_OF_WEEK);
										if (!isToday(onHour, onMin)) {
											if (todayWeek == Calendar.SATURDAY) {
												todayWeek = Calendar.SUNDAY;
											} else {
												todayWeek++;
											}
										}
										DataSupport.updateAll(PowerPlan.class, values, "week = ?",String.valueOf(todayWeek));
									} else {
										String weekString = onWeekString.trim();
										if (weekString.equals("0")) {
											for (int i = 1; i < 8; i++) {
												DataSupport.updateAll(PowerPlan.class, values,"week = ?", String.valueOf(i));
											}
										} else {
											DataSupport.updateAll(PowerPlan.class, values,"week = ?", weekString);
										}
									}
									if (enable) {
										sharedPreferences.edit().putBoolean(POWER_MANAGER_ENABLE, enable).commit();
									}
									mContext.startService(alarmServiceIntent);
								}
							}catch (NumberFormatException e){
								Log.d(TAG, "-----POWER_ON_ACTION-----"+e.toString());
							}
						}
					}
				}else{
					if (!TextUtils.isEmpty(onWeekString)) {
						String weekString = onWeekString.trim();
						if (weekString.equals("0")) {
							for (int i = 1; i < 8; i++) {
								updatePowerOnEnable(false,String.valueOf(i));//Close All
							}
						}else{
							updatePowerOnEnable(false,weekString);
						}
						mContext.startService(alarmServiceIntent);
					}
				}
				Log.d(TAG, "-------------------onWeekString:"+onWeekString+"---onHourString:"+onHourString+"---onMinString:"+onMinString);
			} else if (action.equals(REBOOT_ACTION)) {
				boolean rebootEnable = intent.getBooleanExtra("rebootEnable",false);
				int rebootHour = 0;
				int rebootMin = 0;
				String rebootHourString = intent.getStringExtra("rebootHour");
				String rebootMinString = intent.getStringExtra("rebootMin");
				if(rebootEnable){
					if(!TextUtils.isEmpty(rebootHourString) && !TextUtils.isEmpty(rebootMinString)){
						String tempHour = rebootHourString.trim();
						String tempMin = rebootMinString.trim();
						if(tempHour.length()>0 && tempMin.length()>0){
							try{
								rebootHour = Integer.parseInt(tempHour);
								rebootMin = Integer.parseInt(tempMin);
								if(rebootHour>=0 && rebootHour<24 && rebootMin>=0 && rebootMin<60){
									SharedPreferences sharedPreferences = context.getSharedPreferences("zhao", Context.MODE_PRIVATE);
									Editor editor = sharedPreferences.edit();
									editor.putBoolean("reboot_enable", rebootEnable);
									editor.putInt("reboot_hour", rebootHour);
									editor.putInt("reboot_min", rebootMin);
									editor.apply();
									mContext.startService(alarmServiceIntent);
								}
							}catch (NumberFormatException e){
								Log.d(TAG, "--REBOOT_ACTION--"+e.toString());
							}
						}
					}
				}else{
					SharedPreferences sharedPreferences = context.getSharedPreferences("zhao", Context.MODE_PRIVATE);
					Editor editor = sharedPreferences.edit();
					editor.putBoolean("reboot_enable", rebootEnable);
					editor.apply();
					mContext.startService(alarmServiceIntent);
				}
				Log.d(TAG, "-----------------rebootHourString:" + rebootHourString + "---rebootMinString:" + rebootMinString + "---rebootEnable:" + rebootEnable);
			} else if (action.equals(CLOSE_ALL)) {
				ContentValues values = new ContentValues();
				values.put("enable", false);
				// values.put("onHour", onHour);
				// values.put("onMin", onMin);
				for (int i = 1; i < 8; i++) {
					DataSupport.updateAll(PowerPlan.class, values, "week = ?",String.valueOf(i));
				}
				Log.d(TAG, "--------All power plan is closed----------");
			} else if (action.equals(CAT_ALL)) {
				catAllPowerPlan();
			} else if(action.equals("com.itemp.poweroff")){
				Calendar calendar = Calendar.getInstance();
				int hour = calendar.get(Calendar.HOUR_OF_DAY);
				int min = calendar.get(Calendar.MINUTE);
				int second = calendar.get(Calendar.SECOND);
				int week = calendar.get(Calendar.DAY_OF_WEEK);
				Log.d(TAG, "---It is time to power off " + hour + ":" + min + ":" + second +"_week:"+getWeekString(week));
				context.sendBroadcast(new Intent("ads.android.setpoweroff.action"));
			} else if(action.equals("com.itemp.reboot")){
				Calendar calendar = Calendar.getInstance();
				int hour = calendar.get(Calendar.HOUR_OF_DAY);
				int min = calendar.get(Calendar.MINUTE);
				int second = calendar.get(Calendar.SECOND);
				int week = calendar.get(Calendar.DAY_OF_WEEK);
				Log.d(TAG, "---It is time to reboot " + + hour + ":" + min + ":" + second +"_week:"+getWeekString(week));
				context.sendBroadcast(new Intent("ads.android.setreboot.action"));
			} else if(action.equals("com.itemp.poweroff.update")){
				Calendar calendar = Calendar.getInstance();
				int hour = calendar.get(Calendar.HOUR_OF_DAY);
				int min = calendar.get(Calendar.MINUTE);
				int second = calendar.get(Calendar.SECOND);
				Log.d(TAG, "---com.itemp.poweroff.update---");
				Log.d(TAG, "It is time to upadte power off and reboot time " + hour + ":" + min + ":" + second);
				new Handler().postDelayed(new Runnable() {
					
					@Override
					public void run() {
						mContext.startService(new Intent(mContext, AlarmService.class));
					}
				}, 2000);
			}else if(action.equals("com.itemp.poweron.update")){
				Calendar calendar = Calendar.getInstance();
				int hour = calendar.get(Calendar.HOUR_OF_DAY);
				int min = calendar.get(Calendar.MINUTE);
				int second = calendar.get(Calendar.SECOND);
				Log.d(TAG, "---com.itemp.poweron.update---");
				Log.d(TAG, "It is time to upadte power on time " + hour + ":" + min + ":" + second);
				new Handler().postDelayed(new Runnable() {
					
					@Override
					public void run() {
						mContext.startService(new Intent(mContext, AlarmService.class));
					}
				}, 2000);
			}
		}
	}
	
	private void catAllPowerPlan() {
		StringBuilder stringBuilder = new StringBuilder();
		List<PowerPlan> powerPlans = DataSupport.findAll(PowerPlan.class);
		for (PowerPlan powerPlan : powerPlans) {
			stringBuilder.append(powerPlan.toString() + "\n");
		}
		String allPowerPlan = stringBuilder.toString();
		Intent intent = new Intent("com.android.getAllPowerPlan");
		intent.putExtra("allPowerPlan", allPowerPlan);
		mContext.sendBroadcast(intent);
		Log.d(TAG, allPowerPlan);
	}

	private String getWeekString(int week) {
		switch (week) {
		case 0:
			return "Everyday";
		case 1:
			return "Sunday";
		case 2:
			return "Monday";
		case 3:
			return "Tuesday";
		case 4:
			return "Wednesday";
		case 5:
			return "Thursday";
		case 6:
			return "Friday";
		case 7:
			return "Saturday";
		default:
			return "";
		}
	}

	private boolean isToday(int planHour, int planMin) {
		Calendar calendar = Calendar.getInstance();
		int nowHour = calendar.getTime().getHours();
		int nowMin = calendar.getTime().getMinutes();
		if (planHour > nowHour) {
			return true;
		} else if (planHour == nowHour) {
			if (planMin > nowMin) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	private void updatePowerOnEnable(boolean powerOnEnable, String week) {
		PowerPlan powerPlan = new PowerPlan();
		if (powerOnEnable) {
			powerPlan.setPowerOnEnable(true);
		} else {
			powerPlan.setToDefault("powerOnEnable");
		}
		powerPlan.updateAll("week = ?", week);
	}
	
	private void updatePowerOffEnable(boolean powerOffEnable, String week) {
		PowerPlan powerPlan = new PowerPlan();
		if (powerOffEnable) {
			powerPlan.setPowerOffEnable(true);
		} else {
			powerPlan.setToDefault("powerOffEnable");
		}
		powerPlan.updateAll("week = ?", week);
	}

	// @SuppressLint("NewApi")
	// private void checkAlarmServiceIsRunning(){
	// Log.d(TAG,"-----checkAlarmServiceIsRunning------");
	// AlarmManager alarmManager = (AlarmManager)
	// mContext.getSystemService(Context.ALARM_SERVICE);
	// Intent rebootPlanIntent = new Intent(mContext,AlarmReceiver.class);
	// rebootPlanIntent.setAction("com.itemp.checkalarmservice");
	// PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0,
	// rebootPlanIntent, 0);
	// long alarmTime = SystemClock.elapsedRealtime() +1*60*1000;
	// alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
	// alarmTime, pendingIntent);//Android6.0以上
	// }

	/**
	 * 判断Service是否正在运行
	 * 
	 * @param context
	 *            上下文
	 * @param serviceName
	 *            Service 类全名
	 * @return true 表示正在运行，false 表示没有运行
	 */
	// public boolean isServiceRunning(String serviceName) {
	// ActivityManager manager = (ActivityManager)
	// mContext.getSystemService(Context.ACTIVITY_SERVICE);
	// List<ActivityManager.RunningServiceInfo> serviceInfoList =
	// manager.getRunningServices(200);
	// if (serviceInfoList.size() <= 0) {
	// return false;
	// }
	// for (ActivityManager.RunningServiceInfo info : serviceInfoList) {
	// if (info.service.getClassName().equals(serviceName)) {
	// return true;
	// }
	// }
	// return false;
	// }

}
